package com.apes.fn.scm.appScan;

import com.alibaba.fastjson.JSONArray;
import com.alibaba.fastjson.JSONObject;
import com.apes.framework.jpa.generator.service.SequenceService;
import com.apes.framework.plugin.esb.api.SimpleRequest;
import com.apes.scm.stock.inventory.model.InventoryDiffCompound;
import com.apes.scm.stock.inventory.model.InventoryList;
import com.apes.scm.stock.inventory.repository.InventoryListRepository;
import com.apes.scm.stock.inventory.service.InventoryListService;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Component;
import org.springframework.util.StringUtils;

import java.util.Date;
import java.util.List;
import java.util.Map;
import java.util.stream.Collectors;

/**
 * 盘点单
 */
@Component
public class InventoryTemplate extends SimpleTemplate {

    @Autowired
    private InventoryListService inventoryListService;
    @Autowired
    private InventoryListRepository inventoryListRepository;
    @Autowired
    private SequenceService sequenceService;

    @Override
    public String[] identifys() {
        return new String[]{"PD0"};
    }

    @Override
    public JSONArray getOrderLists(SimpleRequest request, String origin) {
        JSONObject json = request.getJO();
        String localPermitId = json.getString("localPermitId");
        String locationId = json.getString("locationId");

        if (StringUtils.isEmpty(localPermitId) || StringUtils.isEmpty(locationId))  throw new RuntimeException("库区编码和本地权限编码不能为空！");
        List<InventoryList> inventoryLists = inventoryListRepository.findInventoryListBylocalPermitId(locationId, localPermitId);
        return inventoryLists.stream().map(
                inventoryList -> {
                    JSONObject result = new JSONObject();
                    result.put("PDDH", inventoryList.getId());
                    result.put("CKKQID", inventoryList.getWarehouseId().getId());
                    result.put("CKKQMC", inventoryList.getWarehouseId().getName());
                    result.put("CKID", inventoryList.getWarehouseId().getDepot().getId());
                    result.put("CKMC", inventoryList.getWarehouseId().getDepot().getName());
                    result.put("TS01", inventoryList.getVersion());
                    if ("create".equals(inventoryList.getState()) || "inventory".equals(inventoryList.getState())) {
                        result.put("PDLXMC", "初盘");
                        result.put("PDLX", 0);
                        result.put("DJZT", 10);
                    } else {
                        result.put("PDLXMC", "复盘");
                        result.put("PDLX", 1);
                        result.put("DJZT", 20);
                    }
                    result.put("DSB", result.getString("PDDH") + "-" + result.getString("PDLXMC"));
                    return result;
                }
        ).collect(Collectors.toCollection(JSONArray::new));
    }

    @Override
    public void submit(SimpleRequest request) {
        JSONObject requestJO = request.getJO();
        JSONObject params = new JSONObject();
        String id = requestJO.getString("PDDH");
        params.put("id", id);
        int version = requestJO.getInteger("TS01");
        params.put("version", version);
        if (requestJO.getInteger("PDLX") == 0) { // 初盘
            params.put("inventoryListItem", requestJO.getJSONArray("WAR_TMCRKDMX").stream()
                    .map( item -> {
                        JSONObject itemO = (JSONObject) item;
                        JSONObject product = new JSONObject();
                        product.put("id", itemO.getString("SPID"));
                        JSONObject result = new JSONObject();
                        result.put("productId", product);
                        result.put("countQuantity", itemO.getDouble("SMJS") * itemO.getDouble("HSBL"));
                        return result;
                    }).collect(Collectors.toCollection(JSONArray::new))
            );
            request.setData(params);
            inventoryListService.update(request);
        } else {
            InventoryList inventoryList = inventoryListService.findInventoryListById(id);
            if (inventoryList == null) throw new RuntimeException("未找到有效盘点单据！");
            if (version != inventoryList.getVersion()) throw new RuntimeException("盘点单状态已发生改变,请重新查询单据！");
            Map<String, InventoryDiffCompound> diffCompoundMap = inventoryList.getInventoryDiffCompound().stream()
                    .collect(Collectors.toMap(InventoryDiffCompound::acquireProductCode, item -> item));
            requestJO.getJSONArray("WAR_TMCRKDMX").forEach(item -> {
                JSONObject itemO = (JSONObject) item;
                String productId = itemO.getString("SPID");
                if (diffCompoundMap.containsKey(productId)) {
                    diffCompoundMap.get(productId).setCompoundQty(itemO.getDouble("SMJS") * itemO.getDouble("HSBL"));
                } else {
                    InventoryDiffCompound diffCompound = new InventoryDiffCompound();
                    diffCompound.setId(sequenceService.getId(InventoryDiffCompound.CONST_TABLE_NAME));
                    diffCompound.setProductId(getProduct(productId));
                    diffCompound.setUnitId(diffCompound.getProductId().getUom());
                    diffCompound.setCompoundQty(itemO.getDouble("SMJS") * itemO.getDouble("HSBL"));
                    inventoryList.getInventoryDiffCompound().add(diffCompound);
                }
            });
            inventoryList.setState("review");
            inventoryList.setCompoundDate(new Date());
            inventoryListService.saveAndFlush(inventoryList);
        }
    }
}
